<template>
  <div class="app-container">
    <el-row :gutter="24" type="flex" justify="between" class="padding">
      <el-col :span="12" class="titles">
        <span class="title">轮播图管理</span>
      </el-col>
      <el-col :span="12" class="right">
        <el-button type="primary" size="medium" @click="handleAdd">新增轮播图</el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="listLoading"
      :data="list"
      row-key="id"
      border
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="image"
        label="图片"
      >
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.imgUrl"
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="添加时间"
      />
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="title" :visible.sync="dialogForm" width="40%" @close="colse">
      <el-form ref="form" :model="form" size="mini" :rules="rules">
        <el-form-item label="上传图片" :label-width="formLabelWidth" prop="imgUrl">
<!--          <el-upload-->
<!--            ref="upload"-->
<!--            class="upload-demo"-->
<!--            list-type="picture-card"-->
<!--            action="https://www.xunyingcg.com/companyAuth/api/oss/uploadFileToOss"-->
<!--            :on-success="handleAvatarSuccess"-->
<!--            :before-upload="beforeAvatarUpload"-->
<!--            :on-preview="handlePictureCardPreview"-->
<!--            :file-list="fileList"-->
<!--            :limit="1">-->
<!--            <el-button size="small" type="primary" v-if="fileList.length > 1">点击上传</el-button>-->
<!--            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
<!--          </el-upload>-->
          <el-upload
            ref="upload"
            :limit="1"
            :on-exceed="(files, fileList)=>handleExceed(files, fileList, 1)"
            class="avatar-uploader"
            :class="noneBtnDealImg ? 'disUoloadSty':''"
            action="https://www.xunyingcg.com/companyAuth/api/oss/uploadFileToOss"
            :file-list="fileList"
            style="padding:30px 0 ;"
            list-type="picture-card"
            :on-success="(res, file, fileList)=>handleAvatarSuccess(res, file, fileList,'img')"
            :on-preview="handlePictureCardPreview"
            :on-remove="(file,fileList)=>handleRemove(file,fileList,'img')">
            <i class="el-icon-plus" ></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
      <el-dialog :visible.sync="dialogVisible" append-to-body>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { bannerRemove, getBanner, saveBanner } from '@/api/admin/banner'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      dialogForm: false,
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      form: {
        imgUrl: ''
      },
      rules: {
        imgUrl: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ]
      },
      title: '',
      formLabelWidth: '120px',
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      noneBtnDealImg:false,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleExceed(files, fileList, num) {
      this.$message.warning(`当前限制选择 ${num} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleRemove(file, fileList, name) {
      this.form.imgUrl = ''
      this.noneBtnDealImg = fileList.length >= 1
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleAvatarSuccess(response, file, fileList, name) {
      console.log(response)
      this.form.imgUrl = response.data
      this.fileList = []
      this.fileList = fileList
      this.noneBtnDealImg = fileList.length >= 1
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' ||
        file
          .type === 'image/webp'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片JPG或者PNG格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    colse() {
      this.fileList = []
      this.form = {
        imgUrl: ''
      }
    },
    handleAdd() {
      this.dialogForm = true
      this.title = '新增轮播图'
    },
    handleEdit(index, row) {
      this.dialogForm = true
      this.form = JSON.parse(JSON.stringify(row))
      setTimeout(() => {
        this.fileList.push({ name: '', url: this.form.imgUrl })
      }, 500)
      console.log(this.fileList)
      this.title = '修改轮播图'
    },
    submit() {
      this.$refs.form.validate((vaild, done) => {
        if (vaild) {
          if (this.form.parentId) {
            this.form.parentId = this.form.parentId[0]
          }
          saveBanner(this.form).then(response => {
            this.getList()
            this.dialogForm = false
            this.form = {
              imgUrl: ''
            }
            this.$message({
              showClose: true,
              message: response.message,
              type: 'success'
            })
          })
        }
      })
    },
    handleDelete(index, row) {
      this.$confirm(
        '删除',
        '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          bannerRemove(row.id).then(response => {
            this.getList()
            this.$message({
              showClose: true,
              message: response.message,
              type: 'success'
            })
          })
        })
    },
    getList() {
      this.listLoading = true
      getBanner().then(response => {
        this.list = response.data
        this.listLoading = false
      })
    }
  }
}
</script>

<style>
/deep/.el-form-item{
  margin-bottom: 0 !important;
}
/deep/ .crsBanner .el-form-item__label::after {
  content: '(最多1张)';
  display: block;
  font-size: 12px;
  color: #999;
  line-height: 12px;
}

/deep/ .allUpload .el-form-item__content{
  display: flex;
}

/deep/ .el-upload-list__item{
  transition: none !important
}

/deep/ .disUoloadSty .el-upload--picture-card{
  display:none;   /* 上传按钮隐藏 */
}

/deep/ .el-upload-list__item{
  width:300px;
  height:300px;
}
</style>

<style scoped>
.title{
  padding-left: 7px;
  font-size: 16px;
  font-weight: 500;
  line-height: 24px;
}
.right{
  display: flex;
  justify-content: flex-end;
}
.padding{
  margin-bottom: 20px;
}
.titles{
  display: flex;
  align-items: center;
}
.flex{
  padding-top: 20px;
}
</style>
